package com.xingkeduo.service.cms.marketing.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xingkeduo.model.example.TActivityDaysExample;
import com.xingkeduo.model.example.TMarketingCouponBagExample;
import com.xingkeduo.model.example.TMarketingCouponBagExample.Criteria;
import com.xingkeduo.model.example.TMarketingRelevantExample;
import com.xingkeduo.model.param.MarketingParam;
import com.xingkeduo.model.param.MarketingParam.MarketingCouponStatusEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingStatusEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.po.TActivityDays;
import com.xingkeduo.model.po.TMarketingCouponBagWithBLOBs;
import com.xingkeduo.model.po.TMarketingRelevant;
import com.xingkeduo.model.vo.ActivityDaysResponseVo;
import com.xingkeduo.model.vo.MarketingResponseVo;
import com.xingkeduo.service.cms.marketing.MarketingTemplateService;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.DateUtils;
import com.xingkeduo.util.StringUtils;
import com.xingkeduo.util.WeekUtil;
import com.xingkeduo.util.tool.ResponseMessage;

@Service("marketingCouponBagTemplateService")
public class MarketingCouponBagTemplateServiceImpl extends MarketingTemplateServiceImpl implements MarketingTemplateService {
	Logger logger = LoggerFactory.getLogger(MarketingCouponBagTemplateServiceImpl.class);
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage saveOrUpdateCouponByTemplate(MarketingParam couponTemplate) {
		// 实例化CouponBag对象
		TMarketingCouponBagWithBLOBs couponBag = new TMarketingCouponBagWithBLOBs();
		super.buildMarketing(couponTemplate,couponBag);
		// 新券，卡，券包
		if (couponBag.getId() == null) {
			couponBag.setCreateTime(new Date());
			couponBag.setSurplusQuantity(couponBag.getStockQuantity());
			tMarketingCouponBagMapper.insertSelective(couponBag);
			couponTemplate.setId(couponBag.getId());
			// 增加券，卡与服务关联数据，券包与卡，券关联数据,活动时间
			marketingTemplateService.addTMarketingRelevant(couponTemplate);
			return ResponseMessage.ok(couponBag);
		}
		// 老券，卡，券包
		TMarketingCouponBagWithBLOBs oldTMarketingWith = tMarketingCouponBagMapper.selectByPrimaryKey(couponBag.getId());
		if(oldTMarketingWith.getStockQuantity().intValue()>couponTemplate.getStockQuantity().intValue()) {
			return ResponseMessage.error("库存不能低于初始设置",500);
		}
		if (couponBag.getStockQuantity() != null
				&& oldTMarketingWith.getStockQuantity().intValue() != couponBag.getStockQuantity().intValue()) {
			couponBag.setSurplusQuantity(oldTMarketingWith.getSurplusQuantity().intValue()
					+ couponBag.getStockQuantity().intValue() - oldTMarketingWith.getStockQuantity().intValue());
		}
		// 修改服务关联，库存，活动时间
		marketingTemplateService.updateTMarketingRelevant(oldTMarketingWith, couponTemplate);
		tMarketingCouponBagMapper.updateByPrimaryKeySelective(couponBag);
		return ResponseMessage.ok(couponBag);
	}


	@Override
	public ResponseMessage queryCouponById(Long couponBagTemplateId) {
		TMarketingCouponBagWithBLOBs couponBag = tMarketingCouponBagMapper.selectByPrimaryKey(couponBagTemplateId);
		// 赋值活动时间
		MarketingResponseVo responseVo = new MarketingResponseVo();
		BeanUtils.copyProperties(couponBag, responseVo);
		if(StringUtils.isNotBlank(responseVo.getStoreIds())) {
			String storeIds = responseVo.getStoreIds();
			if(storeIds.startsWith("0,")) {
				storeIds = storeIds.substring(2, storeIds.length());
			}
			if(storeIds.endsWith(",0")) {
				storeIds = storeIds.substring(0, storeIds.length()-2);
			}
			responseVo.setStoreIds(storeIds);
		}
		if(StringUtils.isNotBlank(responseVo.getSellStoreIds())) {
			String storeIds = responseVo.getSellStoreIds();
			if(storeIds.startsWith("0,")) {
				storeIds = storeIds.substring(2, storeIds.length());
			}
			if(storeIds.endsWith(",0")) {
				storeIds = storeIds.substring(0, storeIds.length()-2);
			}
			responseVo.setSellStoreIds(storeIds);
		}
		if (couponBag.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			TMarketingRelevantExample tMarketingRelevantExample = new TMarketingRelevantExample();
			tMarketingRelevantExample.createCriteria()
									 .andMarketingIdEqualTo(couponBag.getId())
									 .andStatusEqualTo(Constant.STATUS_YES)
									 .andTotalQuantityGreaterThan(0);
			List<TMarketingRelevant> relevantList = tMarketingRelevantMapper.selectByExample(tMarketingRelevantExample);
			responseVo.setMarketingRelevants(relevantList);
		}
		if (couponBag.getReceiveStartTime().after(new Date())) {
			responseVo.setConponStatus(MarketingCouponStatusEnum.UN_START.getType());
		} else if (couponBag.getReceiveEndTime().before(new Date())) {
			responseVo.setConponStatus(MarketingCouponStatusEnum.OVER.getType());
		} else {
			responseVo.setConponStatus(MarketingCouponStatusEnum.RUNING.getType());
		}
		StringBuffer daysInfo = new StringBuffer();
		if (StringUtils.isNotBlank(couponBag.getWeekHourIds()) && (!"0".equals(couponBag.getWeekHourIds()))) {
			TActivityDaysExample example = new TActivityDaysExample();
			example.createCriteria().andActivityIdEqualTo(couponBagTemplateId)
					.andActivityTypeEqualTo(couponBag.getMarketingType()).andStatusEqualTo(Constant.STATUS_YES);
			List<TActivityDays> activityDaysList = tActivityDaysMapper.selectByExample(example);
			List<ActivityDaysResponseVo> activityDaysResponseList = new ArrayList<ActivityDaysResponseVo>();
			if (CollectionUtils.isEmpty(activityDaysList)) {
				return ResponseMessage.ok(responseVo);
			}
			int size = activityDaysList.size();
			for (int i = 0; i < size; i++) {
				TActivityDays activityDays = activityDaysList.get(i);
				ActivityDaysResponseVo vo = new ActivityDaysResponseVo();
				BeanUtils.copyProperties(activityDays, vo);
				activityDaysResponseList.add(vo);
				String days = activityDays.getDayids();
				if (days.startsWith(",")) {
					days = days.substring(1, days.length());
				}
				if (days.endsWith(",")) {
					days = days.substring(0, days.length() - 1);
				}
				daysInfo.append(WeekUtil.convertWeek(days)).append(", ")
					    .append(DateUtils.formatDate(activityDays.getStartTime(), DateUtils.TIME_FORMAT)).append("~")
					    .append(DateUtils.formatDate(activityDays.getEndTime(), DateUtils.TIME_FORMAT)).append("; ");
			}
			responseVo.setActivityDays(activityDaysResponseList);
		} else {
			//daysInfo.append("日期: 周一至周日; 时间: 0:00 ~ 24:00;");
			daysInfo.append("无限制;");
		}
		responseVo.setDayMemo(daysInfo.toString());
		return ResponseMessage.ok(responseVo);
	}

	@Override
	public ResponseMessage queryCouponByTemplate(MarketingParam couponBagTemplateExample) {
		TMarketingCouponBagExample example = new TMarketingCouponBagExample();
		Criteria criteria = example.createCriteria();
		if (couponBagTemplateExample.getMarketingType() != null) {
			criteria.andMarketingTypeEqualTo(couponBagTemplateExample.getMarketingType());
		}
		// 券Id,券名称
		if (StringUtils.isNumeric(couponBagTemplateExample.getMarketingInfo())) {
			criteria.andIdEqualTo(Long.valueOf(couponBagTemplateExample.getMarketingInfo()));
		} else if (StringUtils.isNotBlank(couponBagTemplateExample.getMarketingInfo())) {
			criteria.andNameLike("%" + couponBagTemplateExample.getMarketingInfo() + "%");
		}
		if (StringUtils.isNotBlank(couponBagTemplateExample.getThirdBizId())) {
				criteria.andThirdBizIdEqualTo(couponBagTemplateExample.getThirdBizId());
		}
		// 领取范围
		if (couponBagTemplateExample.getReceiveType() != null) {
			criteria.andReceiveTypeEqualTo(couponBagTemplateExample.getReceiveType());
		}
		// 券状态
		if (StringUtils.isNotBlank(couponBagTemplateExample.getConponStatus())) {
			MarketingCouponStatusEnum marketCouponStatusEnum = MarketingCouponStatusEnum
					.parse(couponBagTemplateExample.getConponStatus());
			switch (marketCouponStatusEnum) {
			case UN_START:// 未开始˙
				criteria.andReceiveStartTimeGreaterThan(new Date());
				break;
			case RUNING:// 进行中
				criteria.andReceiveStartTimeLessThan(new Date());
				criteria.andReceiveEndTimeGreaterThan(new Date());
				break;
			case OVER:// 已结束
				criteria.andReceiveEndTimeLessThan(new Date());
				break;
			default:
				break;
			}
		}
		// 上下架
		if (couponBagTemplateExample.getStatus() != null) {
			criteria.andStatusEqualTo(couponBagTemplateExample.getStatus());
		}
		// 全部是否开启兑换码
		if (couponBagTemplateExample.getIsOpenConvert() != null) {
			criteria.andIsOpenConvertEqualTo(couponBagTemplateExample.getIsOpenConvert());
		}
		if(couponBagTemplateExample.getCouponBagType()!=null) {
			criteria.andCouponBagTypeEqualTo(couponBagTemplateExample.getCouponBagType());
		}
		if(StringUtils.isNotBlank(couponBagTemplateExample.getCouponInfo()) 
				|| StringUtils.isNotBlank(couponBagTemplateExample.getCardInfo())) {
			List<Long> couponBagList = getRelvevantCouponBagList(couponBagTemplateExample);
			criteria.andIdIn(couponBagList);
		}
		example.setOrderByClause(" id desc");
		PageHelper.startPage(couponBagTemplateExample.getPageNum(), couponBagTemplateExample.getPageSize());
		List<TMarketingCouponBagWithBLOBs> couponBagList = tMarketingCouponBagMapper.selectByExampleWithBLOBs(example);
		PageInfo<TMarketingCouponBagWithBLOBs> page = new PageInfo<>(couponBagList);
		return ResponseMessage.ok(page);
	}

	private List<Long> getRelvevantCouponBagList(MarketingParam couponBagTemplateExample) {
		List<Long> returnList = new ArrayList<>();
		//查看券关联的优惠包id
		if (StringUtils.isNotBlank(couponBagTemplateExample.getCouponInfo())) {
			TMarketingRelevantExample example =new TMarketingRelevantExample();
			com.xingkeduo.model.example.TMarketingRelevantExample.Criteria criteria = example.createCriteria();
			criteria.andMarketingTypeEqualTo(MarketingTypeEnum.COUPON.getCode())
					.andStatusEqualTo(Constant.STATUS_YES)
					.andTotalQuantityGreaterThan(0);
			if (StringUtils.isNumeric(couponBagTemplateExample.getCouponInfo())) {
				criteria.andSupportBusinessIdEqualTo(Long.valueOf(couponBagTemplateExample.getCouponInfo()));
			} else {
				criteria.andServprodNameLike("%" + couponBagTemplateExample.getCouponInfo() + "%");
			}
			List<TMarketingRelevant> relevantList = tMarketingRelevantMapper.selectByExample(example);
			if(!CollectionUtils.isEmpty(relevantList)) {
				returnList.addAll(relevantList.stream().map(relevant -> relevant.getMarketingId()).distinct().collect(Collectors.toList()));
			}
		}
		//查看卡关联的优惠包id
		if (StringUtils.isNotBlank(couponBagTemplateExample.getCardInfo())) {
			TMarketingRelevantExample example =new TMarketingRelevantExample();
			com.xingkeduo.model.example.TMarketingRelevantExample.Criteria criteria = example.createCriteria();
			criteria.andMarketingTypeEqualTo(MarketingTypeEnum.CARD.getCode())
					.andStatusEqualTo(Constant.STATUS_YES)
					.andTotalQuantityGreaterThan(0);
			if (StringUtils.isNumeric(couponBagTemplateExample.getCardInfo())) {
				criteria.andSupportBusinessIdEqualTo(Long.valueOf(couponBagTemplateExample.getCardInfo()));
			} else {
				criteria.andServprodNameLike("%" + couponBagTemplateExample.getCardInfo() + "%");
			}
			List<TMarketingRelevant> relevantList = tMarketingRelevantMapper.selectByExample(example);
			if(CollectionUtils.isEmpty(returnList) 
					&& !CollectionUtils.isEmpty(relevantList)) {
				returnList.addAll(relevantList.stream().map(relevant -> relevant.getMarketingId()).distinct().collect(Collectors.toList()));
			}else if(!CollectionUtils.isEmpty(returnList) 
						&& !CollectionUtils.isEmpty(relevantList)) {
				List<Long> relevants = relevantList.stream().map(relevant -> relevant.getMarketingId()).distinct().collect(Collectors.toList());
				returnList.retainAll(relevants);
			}else if(!CollectionUtils.isEmpty(returnList) 
						&& CollectionUtils.isEmpty(relevantList)){
				returnList.clear();
			}
		}
		if(CollectionUtils.isEmpty(returnList)) {
			returnList.add(0l);
		}
		return returnList;
	}

	@Override
	public ResponseMessage updateCouponStatusById(MarketingParam couponBagTemplate) {
		if(MarketingStatusEnum.UP.getCode() == couponBagTemplate.getStatus().intValue() 
				&& StringUtils.isNotBlank(couponBagTemplate.getThirdBizId())) {
			TMarketingCouponBagExample example = new TMarketingCouponBagExample();
			example.createCriteria()
				   .andStatusEqualTo(couponBagTemplate.getStatus())
				   .andThirdBizIdEqualTo(couponBagTemplate.getThirdBizId())
				   .andIdNotEqualTo(couponBagTemplate.getId());
			int count = tMarketingCouponBagMapper.countByExample(example);
			if(count>0) {
				return ResponseMessage.ok("该套餐id已有相同优惠包并上架，请先下架");
			}
		}
		TMarketingCouponBagWithBLOBs couponBag = new TMarketingCouponBagWithBLOBs();
		couponBag.setId(couponBagTemplate.getId());
		couponBag.setStatus(couponBagTemplate.getStatus());
		couponBag.setUpdateTime(new Date());
		couponBag.setUpdateBy(couponBagTemplate.getUpdateBy());
		tMarketingCouponBagMapper.updateByPrimaryKeySelective(couponBag);
		return ResponseMessage.ok("修改状态成功");
	}
}
